﻿using SqlSugar;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;

namespace LivePlatAPI.Utillity.SqlSquggerExpr
{
    public static class SqlSuggerExp
    {
        public static void SqlSuggerExpMouthed(this WebApplicationBuilder webBuilder)
        {

            string? connectionString = webBuilder.Configuration.GetConnectionString("ConnectionString");
            //Scoped用SqlSugarClient 
            SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.SqlServer,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true,
            },
           db =>
           {
               //SQL执行完
               db.Aop.OnLogExecuted = (sql, pars) =>
               {
                   //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate) 
                   Console.Write("time:" + db.Ado.SqlExecutionTime.ToString());
               };
               db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前
               {
                   //获取原生SQL推荐 5.1.4.63  性能OK
                   UtilMethods.GetNativeSql(sql, pars);
                   Console.WriteLine(sql);
                   //获取无参数化SQL 影响性能只适合调试
                   //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
               };
               db.Aop.OnError = (exp) =>//SQL报错
               {
                   //获取原生SQL推荐 5.1.4.63  性能OK
                   UtilMethods.GetNativeSql(exp.Sql, (SugarParameter[])exp.Parametres);

                   //获取无参数SQL对性能有影响，特别大的SQL参数多的，调试使用
                   //UtilMethods.GetSqlString(DbType.SqlServer, exp.Sql, (SugarParameter[])exp.Parametres);
               };
               db.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值
               {
                   //sql=newsql
                   //foreach(var p in pars) //修改
                   return new KeyValuePair<string, SugarParameter[]>(sql, pars);
               };
           });
            webBuilder.Services.AddScoped(s => sqlSugar);
        }
    }
}
